package com.syl.util;

import com.syl.bean.RequestMsg;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/** http 基本类
 * Created by syl on 2016/6/11.
 */
public class HttpCommon {
    private String charset = "UTF-8";
    private static RequestMsg msg = new RequestMsg();
    private int wait_time = 5000;

    public HttpCommon(){

    }

    public HttpCommon(int wait_time,String encoding){
        this.wait_time = wait_time;
        this.charset = encoding;
    }

    /*
     * 发送get请求
     */
    public RequestMsg send_get_request(String url,Object obj[]){
        url = (url.indexOf("http://") > -1) ? url : ("http://" + url);

        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(wait_time) //设置连接超时时间
                .setSocketTimeout(wait_time) //请求获取数据的超时时间
                .build();

        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig)
                .setRetryHandler(new DefaultHttpRequestRetryHandler());//默认失败后重发3次
        CloseableHttpClient httpclient = httpClientBuilder.build();
        HttpGet httpget = new HttpGet(url);

        try {
            httpget.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31");
            HttpResponse response = httpclient.execute(httpget);
            HttpEntity entity = response.getEntity();
            String html = EntityUtils.toString(entity,charset);
            msg.live = true;
            msg.html = html;
            return  msg;
        } catch (Exception e) {
            msg.live = false;
            msg.html = "连接超时";
            return msg;
        }finally {
            if(httpclient != null) try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public String getCharset() {
        return charset;
    }

    public void setCharset(String charset) {
        this.charset = charset.toUpperCase();
    }
}
